<?php
 /*
 * 文件导出导入
 */
if(!file_exists(dirname(__FILE__)."/phar/PHPExcel.phar")) file_put_contents(dirname(__FILE__)."/phar/PHPExcel.phar", vget("https://cdn.jsdelivr.net/gh/mayoushang/res@1.0/phar/PHPExcel.phar"));
//curl get请求
function vget($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $tmpInfo = curl_exec($curl);
    if (curl_errno($curl)) {
       return '';
    }
    curl_close($curl);
    return $tmpInfo;
}
class ext_excel{
	function __construct(){
		require_once dirname(__FILE__).'/phar/PHPExcel.phar';
		//require_once dirname(__FILE__).'/PHPExcel.phar/IOFactory.php';
	}
	/**
	 * 数据导出
	 * @param string $name 保存路径以及文件名，后缀为xlsx；为空时直接导出
	 * @param array $arr 导出的数据，二维数组 [['ss'=>1111]]
	 * @param array $freewith 自适应宽度列 ['A','B']
	 */
	function write($name='',$table=[],$local = false,$freewith=[]){
		$objPHPExcel = new \PHPExcel();
		// 		echo date('H:i:s') , "设置文档属性" , EOL;
		$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
		->setLastModifiedBy("Maarten Balliauw")
		->setTitle("Office 2007 XLSX Test Document")
		->setSubject("Office 2007 XLSX Test Document")
		->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
		->setKeywords("office 2007 openxml php")
		->setCategory("Test result file");
		$objPHPExcel->getDefaultStyle()->getFont()->setName('Arial')->setSize(10);

		$excel = $objPHPExcel->getActiveSheet();
		$table_count = count($table['data']); //获取行数
		$mi = 1; //定义第一行
		if(!empty($table['name'])){ //如果表头存在
			foreach ($table['name'] as $key => $one) $excel->setCellValue($this->getCellName($key).$mi, " ".$one);
			$mi = 2;
		}
		foreach ($table['data'] as $key => $one){
			if (!empty($table['list'])){ //如果定义了自定义字段
				foreach ($table['list'] as $keys => $ones) $excel->setCellValue($this->getCellName($keys).$mi, " ".$one[$table['list'][$keys]]);
			}else{
				$ti = 0;
				foreach ($one as $keys => $ones){
					$excel->setCellValue($this->getCellName($ti).$mi, " ".$ones);
					$ti++;
				}
			}
			$mi++;
		}

		//自适应宽度
		foreach ($freewith as $v){
			$objPHPExcel->getActiveSheet()->getColumnDimension($v)->setAutoSize(true);
		}
		
		if ($local){
			$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
			$objWriter->save($_SERVER['DOCUMENT_ROOT'].'/'.mb_convert_encoding($name,"gb2312").'.xlsx');
		}else {
			header('Content-Type: application/vnd.ms-excel');
			header('Content-Disposition: attachment;filename="'.mb_convert_encoding($name,"gb2312").'.xls"');
			header('Cache-Control: max-age=0');
			// If you're serving to IE 9, then the following may be needed
			header('Cache-Control: max-age=1');
			
			// If you're serving to IE over SSL, then the following may be needed
			header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
			header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
			header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
			header ('Pragma: public'); // HTTP/1.0
			
			$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			$objWriter->save('php://output');
			exit;
		}
	}

	//循环输出表头字母
	function getCellName($pColumnIndex = 0){
		$_indexCache = array(); 
        if (!isset($_indexCache[$pColumnIndex])) { 
            // Determine column string 
            if ($pColumnIndex < 26) { 
                $_indexCache[$pColumnIndex] = chr(65 + $pColumnIndex); 
            } elseif ($pColumnIndex < 702) { 
                $_indexCache[$pColumnIndex] = chr(64 + ($pColumnIndex / 26)) . chr(65 + $pColumnIndex % 26); 
            } else {
                $_indexCache[$pColumnIndex] = chr(64 + (($pColumnIndex - 26) / 676)) . chr(65 + ((($pColumnIndex - 26) % 676) / 26)) . chr(65 + $pColumnIndex % 26); 
            } 
        } 
        return $_indexCache[$pColumnIndex]; 
	}

	/**
	 * 读取数据 支持exel以及html('xlsx','xlsm','xltx','xltm','xls','xlt','ods','ots','slk','xml','gnumeric','htm','html','csv')
	 * 此处可以使用临时文件路径
	 * @param unknown $filepath
	 * @return multitype:
	 */
	function read($filepath){
		$objPHPExcel = \PHPExcel_IOFactory::load($filepath);
		return $objPHPExcel->getActiveSheet()->toArray();
	}
	
}